package com.allen.excelUtils.format;

import java.util.Map;
import java.util.Map.Entry;

import net.sf.cglib.beans.BeanMap;

import org.apache.poi.ss.usermodel.Cell;

import com.allen.excelUtils.column.Column;
import com.allen.excelUtils.exception.FormatException;
import com.allen.excelUtils.row.DataRow;


/**
 * 普通的行格式化实现类，只负责纯粹数据转换注入
 * @author allen
 *
 * @param <T>
 */
public class RowFormatter2Impl<T> extends RFormatter implements RowFormatter<T> {
	final Class<T> cls;
	BeanMap beanMap;
	Map<String, Column> columnMap;
	
	public RowFormatter2Impl(Class<T> cls){
		this.cls = cls;
		
		try {
			beanMap = BeanMap.create(cls.newInstance());
		} catch (Exception e) {
			throw new FormatException(e);
		}
	}
	
	public T getInstance() throws InstantiationException, IllegalAccessException{
		return cls.newInstance();
	}
	
	@Override
	public T format(DataRow row) throws FormatException {
		columnMap = row.getColumnMap();
		try {
			T obj = getInstance();
			beanMap.setBean(obj);
			for (Entry<String, Column> col : columnMap.entrySet()) {
				Cell cell = row.getCell(col.getKey());
				beanMap.put(col.getKey(), getValue(cell));
			}
			return obj;
		} catch (Exception e) {
			throw new FormatException(e);
		}
	}
}
